// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"fmt"
	"hotgo/internal/dao"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/model/input/form"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

type sSysAuctionBidHistory struct{}

func NewSysAuctionBidHistory() *sSysAuctionBidHistory {
	return &sSysAuctionBidHistory{}
}

func init() {
	service.RegisterSysAuctionBidHistory(NewSysAuctionBidHistory())
}

// Model 出价日志ORM模型
func (s *sSysAuctionBidHistory) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.AuctionBidHistory.Ctx(ctx), option...)
}

// List 获取出价日志列表
func (s *sSysAuctionBidHistory) List(ctx context.Context, in *sysin.AuctionBidHistoryListInp) (list []*sysin.AuctionBidHistoryListModel, totalCount int, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.AuctionBidHistory.Table(), sysin.AuctionBidHistoryListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionBidHistoryListModel{}, &dao.AdminMember, "adminMember"))
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionBidHistoryListModel{}, &dao.AuctionLog, "auctionLog"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.AdminMember.Table(), dao.AuctionBidHistory.Columns().UserId, "=", dao.AdminMember.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.AuctionLog.Table(), dao.AuctionBidHistory.Columns().LogId, "=", dao.AuctionLog.Columns().Id)

	// 查询id
	if in.Id > 0 {
		mod = mod.Where(dao.AuctionBidHistory.Columns().Id, in.Id)
	}

	// 查询拍品id
	if in.LogId > 0 {
		mod = mod.Where(dao.AuctionBidHistory.Columns().LogId, in.LogId)
	}

	// 查询出价用户
	if in.UserId > 0 {
		mod = mod.Where(dao.AuctionBidHistory.Columns().UserId, in.UserId)
	}

	// 查询创建日期
	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(dao.AuctionBidHistory.Columns().CreatedAt, in.CreatedAt[0], in.CreatedAt[1])
	}

	// 查询日期
	if in.AuctionLogDate != nil {
		mod = mod.WherePrefix(dao.AuctionLog.Table(), dao.AuctionLog.Columns().Date, in.AuctionLogDate)
	}

	// 查询开始时间
	if in.AuctionLogStartTime != nil {
		mod = mod.WherePrefix(dao.AuctionLog.Table(), dao.AuctionLog.Columns().StartTime, in.AuctionLogStartTime)
	}

	// 查询结束时间
	if in.AuctionLogEndTime != nil {
		mod = mod.WherePrefix(dao.AuctionLog.Table(), dao.AuctionLog.Columns().EndTime, in.AuctionLogEndTime)
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.AuctionBidHistory.Table() + "." + dao.AuctionBidHistory.Columns().Id)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取出价日志列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出出价日志
func (s *sSysAuctionBidHistory) Export(ctx context.Context, in *sysin.AuctionBidHistoryListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(sysin.AuctionBidHistoryExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出出价日志-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []sysin.AuctionBidHistoryExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增出价日志
func (s *sSysAuctionBidHistory) Edit(ctx context.Context, in *sysin.AuctionBidHistoryEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 修改
		if in.Id > 0 {
			if _, err = s.Model(ctx).
				Fields(sysin.AuctionBidHistoryUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.Wrap(err, "修改出价日志失败，请稍后重试！")
			}
			return
		}

		// 新增
		if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(sysin.AuctionBidHistoryInsertFields{}).
			Data(in).OmitEmptyData().Insert(); err != nil {
			err = gerror.Wrap(err, "新增出价日志失败，请稍后重试！")
		}
		return
	})
}

// Delete 删除出价日志
func (s *sSysAuctionBidHistory) Delete(ctx context.Context, in *sysin.AuctionBidHistoryDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除出价日志失败，请稍后重试！")
		return
	}
	return
}

// View 获取出价日志指定信息
func (s *sSysAuctionBidHistory) View(ctx context.Context, in *sysin.AuctionBidHistoryViewInp) (res *sysin.AuctionBidHistoryViewModel, err error) {
	if err = s.Model(ctx).WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取出价日志信息，请稍后重试！")
		return
	}
	return
}

// ApiList 获取出价日志列表
func (this *sSysAuctionBidHistory) ApiList(ctx context.Context, in *sysin.AuctionBidHistoryApiListInp) (list *sysin.AuctionBidHistoryListModel, totalCount int, err error) {
	mod := this.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.AuctionBidHistory.Table(), sysin.AuctionBidHistoryListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionBidHistoryListModel{}, &dao.AdminMember, "adminMember"))
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionBidHistoryListModel{}, &dao.AuctionLog, "auctionLog"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.AdminMember.Table(), dao.AuctionBidHistory.Columns().UserId, "=", dao.AdminMember.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.AuctionLog.Table(), dao.AuctionBidHistory.Columns().LogId, "=", dao.AuctionLog.Columns().Id)

	// 查询拍品id
	if in.LogID > 0 {
		mod = mod.Where(dao.AuctionBidHistory.Columns().LogId, in.LogID)
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.AuctionBidHistory.Table() + "." + dao.AuctionBidHistory.Columns().Id)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取出价日志列表失败，请稍后重试！")
		return
	}
	return
}

// ApiRank 获取出价日志列表
func (this *sSysAuctionBidHistory) ApiRank(ctx context.Context, in *sysin.AuctionBidHistoryApiListInp) (list []*sysin.AuctionBidHistoryListModel, totalCount int, err error) {
	mod := this.Model(ctx)

	mod = mod.Raw(`
SELECT
    ranked_bids.id,
	ranked_bids.log_id,
	ranked_bids.user_id,
	ranked_bids.bid_amount,
	ranked_bids.created_at,
	hg_admin_member.real_name AS adminMemberRealName,
	hg_admin_member.username AS adminMemberUsername,
	hg_admin_member.avatar AS adminMemberAvatar,
	hg_admin_member.nickname AS adminMemberNickname,
	hg_auction_log.DATE AS auctionLogDate,
	hg_auction_log.start_time AS auctionLogStartTime,
	hg_auction_log.end_time AS auctionLogEndTime 
FROM
	(SELECT *, 
	ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY bid_amount DESC, created_at DESC) AS user_rank FROM hg_auction_bid_history WHERE log_id = ?) AS ranked_bids
	LEFT JOIN hg_admin_member ON ranked_bids.user_id = hg_admin_member.id
	LEFT JOIN hg_auction_log ON ranked_bids.log_id = hg_auction_log.id 
WHERE
	ranked_bids.user_rank = 1 
	
ORDER BY
	ranked_bids.bid_amount DESC
`, in.LogID)

	// 分页
	if in.Pagination {
		mod = mod.Page(in.Page, in.PerPage)
	}

	//mod = mod.Group(dao.AuctionBidHistory.Columns().UserId)
	//// 排序
	//mod = mod.OrderDesc(dao.AuctionBidHistory.Table() + "." + dao.AuctionBidHistory.Columns().BidAmount)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取出价日志列表失败，请稍后重试！")
		return
	}
	return
}
